import os

from google.appengine.api import users
from google.appengine.ext import db
from google.appengine.ext.db import djangoforms

import django
from django import http
from django import shortcuts

from sendemail.models import *
from sendemail.helper import *
from sendemail.sql import *
from sendemail.sessions import *
from conf.settings import *
 
def check_ajax(request):
  params = {}
  now = datetime.date.today()
  item = None
  name = SafeGet("user",None,request)
  password = SafeGet("password",None,request)
  item = VUser.gql("WHERE name=:1 AND password=:2",name,password).get()
  
  xml = "<user>"
  if item is None:
      xml += tagify('result','Error')
      xml += tagify('msg','Invalid user and password')
      xml += "</user>"
      response = http.HttpResponse(xml,mimetype='text/xml')
      return response 
  
  if item.expire_date > now:
      xml += tagify('result','Success')
      xml += tagify('user',item.name)
      xml += tagify('password',item.password)
      xml += tagify('expire_date',item.expire_date)
      xml += tagify('status',item.status)
  else:
      xml += tagify('result','Error')
      xml += tagify('msg','expire date')  
  
  xml += "</user>"
  response = http.HttpResponse(xml,mimetype='text/xml')
  return response 
  
def list(request):
  params = {}
  vUsers = VUser.all()
  p = int(SafeGet('page',0,request))+1
  StringPaging = paging(vUsers.count(),'?page=',PAGE_SIZE,p)
  
  vUsers = vUsers.fetch(PAGE_SIZE,((p-1)*PAGE_SIZE))
 
  params['Title'] = 'List User'
  params['items'] = vUsers
  params['StringPaging'] = StringPaging
  
  return respond(request, None, 'vuser_list', params)

def delete(request, idItem):
  item = None
  if idItem:
    item = VEmailContent.get_by_id(int(idItem))
    if item is None:
      return http.HttpResponseNotFound('No Item')
  
  item.delete()
  return http.HttpResponseRedirect('/vcontent')

def add(request):
  return edit(request, None)

def edit(request, idItem):
  params = {}
  params['Title'] = 'Add new User'
    
  item = None
  if idItem:
    item = VUser.get_by_id(int(idItem))
    if item is None:
      return http.HttpResponseNotFound('No Item')
  
  params['item'] = item
  
  if not request.POST:
      return respond(request, None, 'vuser_edit', params)
  
  if item is None:
    item = VUser()
       
  try:            
      item.name   = db.Email(SafePost('name',None,request))
      item.password  = SafePost('password','',request)
      item.status   = int(SafePost('status',0,request))
      item.expire_date = DateRealToDB(SafePost('expire_date',None,request))
  except db.Error, err:
      params['err'] = err
      params['item'] = item
      return respond(request, None, 'vuser_edit', params)
  
  item.put()

  return http.HttpResponseRedirect('/vuser')


